from rest_framework.views import APIView
from random import randint
import logging
from django_redis import get_redis_connection
from rest_framework.response import Response
from .constants import VERIFY_CODE_REDIS_EXPIRE, SEND_VERIFY_CODE_INTERVAL
from celery_tasks.verifyCode.tasks import send_verify_code
logger = logging.getLogger('django')


class VerificationCode(APIView):
  def get(self, request, mobile):
    redis_conn = get_redis_connection('verify_codes')
    send_flag = redis_conn.get('send_flag_%s' % mobile)
    if send_flag:
        return Response({'message': '发送过于频繁'})
    verify_code = '%06d' % randint(0, 999999)
    logger.info(verify_code)
    # 使用管道减少redis的多次执行操作
    pl = redis_conn.pipeline()
    pl.setex('verify_%s' % mobile, VERIFY_CODE_REDIS_EXPIRE, verify_code)
    pl.setex('send_flag_%s' % mobile, SEND_VERIFY_CODE_INTERVAL, 1)
    pl.execute()
    # send_verify_code.delay('1156606727@qq.com', '注册', verify_code, VERIFY_CODE_REDIS_EXPIRE//5)

    return Response({'message': 'ok', 'verifyCode': verify_code})


